<template>
  <layout-card :filters="goodsReceiveOptions" @search-change="searchChange" headline="信息列表" @search-reset="searchReset">
    <template #index="{ row }">
      {{ (pager.currentPage - 1) * pager.pageSize + row['index'] + 1 }}
    </template>
    <template #action>
      <el-button type="primary" @click="handleExport">导出</el-button>
    </template>
    <table-common :columns="goodsReceiveColumns" :loading="loading" :pagination="pager" :table-data="tableData"
      size="large" @current-change="currentChange" @size-change="sizeChange">
      <template #action="{ row }">
        <!-- 自定义操作栏示例  -->
        <el-button class="link-btn" @click="handleDetail(row['regId'], row['taskId'])" link type="primary">查看</el-button>
      </template>
    </table-common>
  </layout-card>
  <Detail :visible="centerDialogVisible"  :info="storeDetail" @cancel="Cancel"/>
  </template>

<script lang="ts" setup>
import { ref, reactive, onBeforeMount, computed, watch } from 'vue'
import LayoutCard from '@/components/LayoutCard/index.vue'
import TableCommon from '@/components/TableCommon/index.vue'
import { goodsReceiveOptions } from './config/filters'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage, TableColumnCtx, dayjs } from 'element-plus'
import { goodsReceive, exportGoods } from '@/api/lose/goodsReceive'
import { pickUpGoodsDetail } from '@/api/lose/goodsReg'
import { useStore } from 'vuex'
import { deleteFile } from '@/api/common'
import Detail from './detail.vue'
import { goodsTypeList } from '@/api/lose/goodsType'

// 新增弹窗是否打开
const centerDialogVisible = ref(false)
// 弹窗标题
const store = useStore()
const storeDetail = ref({})
interface GoodsReceiveListItem {
  goodsType: string;
  goodsName: string;
  goodsCode: string;
  receiveName: string;
  depositTerminal: string;
  receiveTime: string;
  userName: string;
}
const goodsReceiveColumns = [
  {
    prop: 'index',
    type: 'index',
    label: '序号',
    index: function (index: number) {
      return (pager.currentPage - 1) * pager.pageSize + index + 1
    },
    width: 60,
    align: 'center'
  },
  {
    prop: 'goodsType',
    label: '物品类型',
    minWidth: 130,
    align: 'center',
    formatter: function (row: GoodsReceiveListItem, column: TableColumnCtx<GoodsReceiveListItem>, cellValue: string) {
      return store.getters['goodsType/getGoodsTypeName'](cellValue)
    }
  },
  { prop: 'goodsName', label: '物品名称', minWidth: 200, align: 'center' },
  { prop: 'goodsCode', label: '物品编号', minWidth: 120, align: 'center' },
  { prop: 'receiveName', label: '领取人', minWidth: 120, align: 'center' },
  { prop: 'depositTerminal', label: '航站楼【领取】', minWidth: 120, align: 'center' },
  {
    prop: 'receiveTime',
    label: '领取时间',
    // sortable: true,
    minWidth: 180,
    align: 'center',
    formatter: function (row: GoodsReceiveListItem, column: TableColumnCtx<GoodsReceiveListItem>, cellValue: string) {
      return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
    }
  },
  { prop: 'userName', label: '记录人', minWidth: 120, align: 'center' },
  { prop: 'action', label: '操作', fixed: 'right', align: 'center' }
]

/**
 * 导出
 */
const handleExport = () => {
  if (Array.isArray(search.value.depositTerminal)) {
    search.value.depositTerminal.length === 0 ? delete search.value.depositTerminal : search.value.depositTerminal = search.value.depositTerminal.join(',')
  }
  if (Array.isArray(search.value.goodsType)) {
    search.value.goodsType.length === 0 ? delete search.value.goodsType : search.value.goodsType = search.value.goodsType.join(',')
  }
  if (Array.isArray(search.value.startTime)) {
    if (search.value.startTime.length > 0) {
      const date = search.value.startTime
      search.value.startTime = date[0] + ' 00:00:00'
      search.value.endTime = date[1] + ' 23:59:59'
    } else {
      delete search.value.startTime
    }
  }
  if (tableData.value.length === 0) {
    ElMessage.error('当前没有可导出的数据')
    return
  }
  exportGoods(search.value).then(res => {
    const data: any = res
    if (!data) {
      ElMessage.error('当前没有可导出的数据')
      return 
    }
    const name = '物品领取记录'+dayjs().format('YYYYMMDDHHmmss') + '.xlsx'
    const url = window.URL.createObjectURL(data)
    const aLink = document.createElement('a')
    aLink.style.display = 'none'
    aLink.href = url
    aLink.setAttribute('download', name)
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink) // 下载完成移除元素
    window.URL.revokeObjectURL(url) // 释放掉blob对象
  }).catch(err => {
    ElMessage.error(err.message || '导出失败')
  })
}

/**
 * 查看详情
 */
const handleDetail = (regId: string, taskId: string) => {
  centerDialogVisible.value = true
  storeDetail.value = {
    regId: regId,
    taskId: taskId
  }
}

/**
 * 弹窗点击取消
 */
const Cancel = () => {
  centerDialogVisible.value = false
}

const loading = ref(false)
const tableData = ref([])
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const search = ref<FilterDataType>({})

/**
 * 获取物品领取记录
 */
const getData = () => {
  loading.value = true
  if (Array.isArray(search.value.depositTerminal)) {
    search.value.depositTerminal.length === 0 ? delete search.value.depositTerminal : search.value.depositTerminal = search.value.depositTerminal.join(',')
  }
  if (Array.isArray(search.value.goodsType)) {
    search.value.goodsType.length === 0 ? delete search.value.goodsType : search.value.goodsType = search.value.goodsType.join(',')
  }
  if (Array.isArray(search.value.startTime)) {
    if (search.value.startTime.length > 0) {
      const date = search.value.startTime
      search.value.startTime = date[0] + ' 00:00:00'
      search.value.endTime = date[1] + ' 23:59:59'
    } else {
      delete search.value.startTime
    }
  }

  const params = {
    pageNum: pager.currentPage,
    pageSize: pager.pageSize,
    condition: search.value
  }
  goodsReceive(params).then(res => {
    console.log(res)
    if (res.data) {
      loading.value = false
      const data: Array<any> = res.data.list
      data.forEach(ele => {
        ele.userName = ele.creator.name
      })
      // @ts-ignore
      tableData.value = data
      pager.total = res.data.total
    }
  }).catch(() => {
    loading.value = false
  })
}

// 分页
const sizeChange = (size: number) => {
  pager.pageSize = size
  getData()
}
const currentChange = (value: number) => {
  pager.currentPage = value
  getData()
}
/**
 * 点击查询
 */
const searchChange = (data: FilterDataType) => {
  search.value = data
  getData()
}
// 点击导出
// const handleExport


/**
 * 点击重置
 * @param data 数据
 */
const searchReset = (data: FilterDataType) => {
  search.value = data
  pager.currentPage = 1
  pager.pageSize = 10
  getData()
}
const loadTerminal = () => {
  store.dispatch('terminal/getDict')
}

// const loadGoodsType = () => {
//   goodsTypeList({}).then((res: any) => {
//     if (res?.code === '1') {
//       if (res && res.data) {
//         const { data } = res
//         const options = [
//           ...data.map((item: any) => ({ label: item.goodsType, value: item.typeId }))]
//         goodsReceiveOptions.value[6].inputProps.options = options
//       }
//     }
//   })
// }
const loadGoodsType = () => {
  store.dispatch('goodsType/getGoodsType')
}

watch(
  () => store.state.goodsType.typeList, () => {
    const options: Array<any> = []
    store.state.goodsType.typeList.forEach((ele: any) => {
      options.push({ label: ele.goodsType, value: ele.typeId })
    })
    goodsReceiveOptions.value[6].inputProps.options = options
  }
)
watch(
  () => store.state.terminal.data, () => {
    const options: Array<any> = []
    store.state.terminal.data.forEach((ele: any) => {
      options.push(ele)
    })
    goodsReceiveOptions.value[5].inputProps.options = options
  }
)
const initData = () => {
  // 获取航站楼
  loadTerminal()
  // 获取物品类型
  loadGoodsType()
  // 获取记录
  getData()
}

onBeforeMount(initData)
</script>
<style lang="less" scoped>
  @import url("./index.less");
</style>
